import java.util.ArrayList;
import java.util.List;

public class demo1 {
    int sum=0;
    int[]temp;
    int[]index;
    int []setindex;
    int []ret;//获取答案的数组
    ArrayList<Integer> list=new ArrayList<>();
    public List<Integer> countSmaller(int[] nums) {
        temp=new int[nums.length];//注意提前定义
        index=new int[nums.length];
        setindex=new int[nums.length];
        ret=new int[nums.length];
        //定义标记下标的数组
        for(int i=0;i<nums.length-1;i++){
            index[i]=i;
        }
        gbin(nums,0,nums.length-1);
        for(int y:ret){
            list.add(y);
        }
        return list;
    }
    public void gbin(int[]nums,int left,int right){
        int sum=0;
        if(left>=right)return ;
        int mid=(left+right)/2;
        //先将数组左右分组再进行合并
        gbin(nums,left,mid);
        gbin(nums,mid+1,right);
        int cur1=left,cur2=mid+1,x=0;
        while(cur1<=mid&&cur2<=right){
            // 降序
            if(nums[cur1]<=nums[cur2]){
                temp[x]=nums[cur2];
                setindex[x++]=index[cur2++];
            }else{
                temp[x]=nums[cur1];
                setindex[x]=index[cur1];
                ret[index[cur1]]+=right-cur2+1;//一定需要+=因为分组原因导致符合条件的答案被分到不同的归并组中
                cur1++;
                x++;
            }
        }
        //list.add(sum);
        while(cur1<=mid){
            setindex[x]=index[cur1];
            temp[x++]=nums[cur1++];
        }
        while(cur2<=right){
            setindex[x]=index[cur2];
            temp[x++]=nums[cur2++];
        }
        for(int i=left;i<=right;i++){
            nums[i]=temp[i-left];
            index[i]=setindex[i-left];
        }

    }
}
